//
//  HMNetworkTools.swift
//  3.Swift中网络的封装
//
//  Created by heima on 16/4/8.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import AFNetworking

//swift 中的枚举
enum HMHttpMethods: String {
    case POST = "POST"
    case GET = "GET"
}
class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
    //封装所有的网络请求方法 所有的网络请求都是通过这个方法和 AFN进行联系
    func request(method: HMHttpMethods,urlString: String, parameters: AnyObject?, finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        //swift中就不能够使用利用协议 欺骗Xcode
        //为了达到封装的目的 可以将相同的闭包 抽取出来,当做参数传递给AFN框架
        let success =  { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            //执行成功的回调
            finished(result: result, error: nil)
        }
        
        //定义失败的回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            //执行失败的回调
            finished(result: nil, error: error)
        }
        
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
//        if method == .GET {
//            GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
//                //执行成功的回调
//                finished(result: responseObject, error: nil)
//                }, failure: { (_, error) -> Void in
//                    //执行失败的回调
//                    finished(result: nil, error: error)
//            })
//        } else {
//            POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
//                //执行成功的回调
//                finished(result: responseObject, error: nil)
//                }, failure: { (_, error) -> Void in
//                    //执行失败的回调
//                    finished(result: nil, error: error)
//            })
//        }
    }
    
    /*
    HMNetworkTools.sharedTools.GET(urlString, parameters: nil, progress: nil, success: { (_, responseObject) -> Void in
    print(responseObject)
    }) { (_, error) -> Void in
    print(error)
    }
    */
}
